package com.ttt.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttt.pojo.Student;
import com.ttt.service.RegisterService;
import com.ttt.service.UserLoginService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/RegisterServerController")
public class RegisterServerController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Student student = new Student();
        //获取前端发来的信息
        String id = req.getParameter("id");
        student.setId(id);
        String name = req.getParameter("name");
        student.setName(name);
        String gender = req.getParameter("gender");
        student.setGender(gender);
        String college = req.getParameter("college");
        student.setCollege(college);
        String major = req.getParameter("major");
        student.setMajor(major);
        String grade = req.getParameter("grade");
        student.setGrade(grade);
        String phone = req.getParameter("phone");
        student.setPhone(phone);
        String password = req.getParameter("password");
        student.setPassword(password);

        System.out.println("进入到servlet");

        RegisterService registerService = new RegisterService();
        UserLoginService userLoginService = new UserLoginService();
        //判断数据库里面使用有该学生，如果没有，进行注册，如果有提示已有该学生
        //存储返回值，如果学生注册的信息数据库里面已经存在，则放回false,反之进行数据插入操作，返回true
        boolean mes = false;
        try {
            System.out.println("进入到userLoginService.findByUser(id)");
            boolean byUser = userLoginService.findByUser(id);
            if (!byUser){  //不存在
                //将学生注册的信息放在数据库
                try {
                    System.out.println("进入到 registerService.inserteStudents(student);");
                    registerService.inserteStudents(student);
                    mes = true;
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //将返回结果返回给前端，也就是：mes,

        // 构建前端需要的JSON格式
        Map<String, Object> responseData = new HashMap<>();

        responseData.put("mes",mes);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        // 设置响应头
        resp.setContentType("application/json");
        // 输出响应
        PrintWriter out = resp.getWriter();
        out.print(json);
        System.out.println(json);




    }
}
